package com.ccm.demo.rediscache.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
@EnableTransactionManagement
public class DruidDBConfig implements EnvironmentAware{

	private RelaxedPropertyResolver property;

	@Override
	public void setEnvironment(Environment environment) {
		this.property=new RelaxedPropertyResolver(environment,"spring.datasource.");
	}

	@Bean
	@Primary
	public DataSource dataSource(){
		DruidDataSource dataSource=new DruidDataSource();
		dataSource.setDriverClassName(property.getProperty("driver-class-name"));
		dataSource.setUrl(property.getProperty("url"));
		dataSource.setUsername(property.getProperty("username"));
		dataSource.setPassword(property.getProperty("password"));
		dataSource.setInitialSize(Integer.valueOf(property.getProperty("initialSize")));
		dataSource.setMaxActive(Integer.valueOf(property.getProperty("maxActive")));
		dataSource.setMinIdle(Integer.valueOf(property.getProperty("minIdle")));
		dataSource.setMaxWait(Long.valueOf(property.getProperty("maxWait")));
		dataSource.setTimeBetweenEvictionRunsMillis(Long.valueOf(property.getProperty("timeBetweenEvictionRunsMillis")));
		dataSource.setMinEvictableIdleTimeMillis(Long.valueOf(property.getProperty("minEvictableIdleTimeMillis")));
		dataSource.setValidationQuery("SELECT 'x'");
		dataSource.setTestOnBorrow(true);
		dataSource.setTestOnReturn(false);
		dataSource.setTestWhileIdle(true);
		try {
			dataSource.setFilters("wall");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return dataSource;
	}
}
